﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using NetWing.Model;//系统所有的model 都在这个命名空间里，这个还是比较有好处的。
using NetWing.BPM.Core;
using NetWing.Common;
using System.Text;
using Omu.ValueInjecter;
using NetWing.Common.Data;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using NetWing.BPM.Core.Bll;
using NetWing.BPM.Core.Model;
using NetWing.BPM.Core.Dal;

namespace NetWing.BPM.Admin.mjorderdetail.ashx
{
    /// <summary>
    /// MJOrderXF 的摘要说明
    /// </summary>
    public class MJOrderXF : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {           
            //context.Response.Write("Hello World");
            context.Response.ContentType = "text/plain";
            if (SysVisitor.Instance.cookiesDepartments == "0")//说明没有数据权限
            {
                context.Response.Write(
                    new JsonMessage { Success = false, Data = "-99", Message = "登录已过期，请重新登录" }.ToString()
                    );
                context.Response.End();
            }
            //
            string checkLogin = SysVisitor.Instance.cookiesUserDepId;
            if (string.IsNullOrEmpty(checkLogin))
            {
                context.Response.Write("{\"status\":0,\"msg\":\"登录已过期，请退出重新登录！\"}");
                context.Response.End();
            }

            #region 公共变量
            int fmainInsertedId = 0;//财务主表插入的ID
            var main = HttpContext.Current.Request["main"];//得到主表json数据
            var detail = HttpContext.Current.Request["detail"];//得到明细表json数据
            //以后统一单号。续费的就是XF
            string edNumber = common.mjcommon.getedNumber("XF");//得到此次财务订单号，原来是浏览器给，现在从系统获取
            string roomid = context.Request["roomid"];//房间id
            string userids = context.Request["userids"];//用户id
            string orderid = context.Request["orderid"];//主订单id
            decimal payment = 0;//支付总额
            decimal total = decimal.Parse(context.Request["total"]);//合计金额
            string account = "";//
            int accountid = 0;//

            string contact = context.Request["contact"];//经手人
            int contactid = int.Parse(context.Request["contactid"]);//经手人ID
            //得到订单信息，使之作为主变量
            DataTable mainOrderDt = SqlEasy.ExecuteDataTable("select * from MJOrder where Keyid=" + orderid + "");
            string mainOrderjson = JSONhelper.ToJson(mainOrderDt);
            var mainobj = JSONhelper.ConvertToObject<MJOrderModel>(mainOrderjson.Replace("[", "").Replace("]", ""));//根据模型把json数据转化为obj
            MJOrderModel mainOrderModeltemp = new MJOrderModel();//初始化主表模型
            mainOrderModeltemp.InjectFrom(mainobj);//把obj插入模型
            #endregion
            #region 收款账号处理
            //account 作为总量  accountb accountc accountd 作为子项
            int c = 1;//收款方式有几种
            string accountb = "";
            string accountidb = "0";
            string shifub = "0";

            string accountc = "";
            string accountidc = "0";
            string shifuc = "0";

            string accountd = "";
            string accountidd = "0";
            string shifud = "0";

            string accounts = context.Request["account"];//收款账号
            string accountids = context.Request["accountid"];//收款账号ID
            string shifus = context.Request["shifu"];//实付
            string[] accountarr = null;
            string[] accountidarr = null;
            string[] shifuarr = null;
            if (!string.IsNullOrEmpty(accounts))//不为空
            {
                if (accounts.IndexOf(",") > -1)//包含，说明有多个
                {
                    accountarr = accounts.Split(',');
                    accountidarr = accountids.Split(',');
                    shifuarr = shifus.Split(',');
                    c = accountidarr.Length;//计算有几个从0开始
                    switch (c)
                    {
                        case 2://2个

                            accountb = accountarr[0];
                            accountidb = accountidarr[0];
                            shifub = shifuarr[0];
                            accountc = accountarr[1];
                            accountidc = accountidarr[1];
                            shifuc = shifuarr[1];

                            account = accounts;//收款账号为多账户
                            accountid = 0;//如果多账号为0
                            payment = decimal.Parse(shifub) + decimal.Parse(shifuc);//实付金额为两个账号加起来
                            break;
                        case 3://3个
                            accountb = accountarr[0];
                            accountidb = accountidarr[0];
                            shifub = shifuarr[0];
                            accountc = accountarr[1];
                            accountidc = accountidarr[1];
                            shifuc = shifuarr[1];
                            accountd = accountarr[2];
                            accountidd = accountidarr[2];
                            shifud = shifuarr[2];

                            account = accounts;//收款账号为多账户
                            accountid = 0;//如果多账号为0
                            payment = decimal.Parse(shifub) + decimal.Parse(shifuc) + decimal.Parse(shifud);//实付金额为几个账号加起来
                            break;
                        default:
                            break;
                    }

                }
                else//说明只有一个
                {
                    account = accounts;
                    accountid = int.Parse(accountids);
                    payment = decimal.Parse(shifus);
                    //如果是一个的情况 给第一个accountb的相关值
                    accountb = account;
                    accountidb = accountid.ToString();
                    shifub = payment.ToString();



                }

            }
            #endregion


            //实收金额可以为0
            //if (payment == 0)
            //{
            //    context.Response.Write("{\"status\":0,\"msg\":\"失败！实收金额不能为0！\"}");
            //    context.Response.End();
            //}


            #region 财务主表处理
            //财务主表处理 方便以后财务统计s
            MJFinanceMainModel fmainModel = new MJFinanceMainModel();//初始化财务主表
            fmainModel.account = account;//账号
            fmainModel.accountid = accountid;//账号ID
            //多收款账号处理
            fmainModel.accountb = accountb;
            fmainModel.accountidb = int.Parse(accountidb);
            fmainModel.shifub = decimal.Parse(shifub);
            fmainModel.accountc = accountc;
            fmainModel.accountidc = int.Parse(accountidc);
            fmainModel.shifuc = decimal.Parse(shifuc);
            fmainModel.accountd = accountd;
            fmainModel.accountidd = int.Parse(accountidd);
            fmainModel.shifud = decimal.Parse(shifud);
            //多收款账号处理end



            fmainModel.add_time = DateTime.Now;
            fmainModel.contact = contact;
            fmainModel.contactid = contactid;
            //fmainModel.dep = dep;//部门
            fmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
            fmainModel.edNumber = edNumber;
            fmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
            fmainModel.unit = mainOrderModeltemp.users;//用户
            fmainModel.unitid = mainOrderModeltemp.usersid;//用户ID
            fmainModel.note = mainOrderModeltemp.users + "续费收据";
            fmainModel.payment = payment;
            fmainModel.total = total;
            fmainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserId);
            fmainModel.operate = SysVisitor.Instance.cookiesUserName;
            fmainModel.paytype = mainOrderModeltemp.paytype;//支付方式
            fmainModel.nextpaydate = mainOrderModeltemp.nextpaydate;//下次支付时间
            fmainModel.roomid = mainOrderModeltemp.roomid;
            fmainModel.roomno = mainOrderModeltemp.roomno;
            fmainModel.orderid = mainOrderModeltemp.KeyId;//订单编号

            MJFinanceMainModel financemainmodeltemp = fmainModel;//公共变量以后使用

            //财务主表处理 方便以后财务统计e
            #endregion


            #region 子表明细表处理
            JArray detailArr = JArray.Parse(detail);//把明细表转化为数组
            var k = detailArr[0].ToString();
            #endregion
            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {
                fmainInsertedId = DbUtils.tranInsert(fmainModel, tran);//财务主表插入一条 并提交事务
                #region 续费更新处理
                int ccc = 0;//续费新增计数器 如果都没有续费新增则退出
                string findetailsql = "";//财务明细表sql语句
                //循环明细表
                for (int i = 0; i < detailArr.Count; i++)//有几条就执行几次
                {

                    string type = detailArr[i]["type"].ToString();
                    switch (type)
                    {
                        case "续费"://服务项目不变，财务主表，明细表有更新。
                            ccc = ccc + 1;
                            string xufeisql = orderDetailxf((JObject)detailArr[i]);//订单续费 更新订单
                            DbUtils.tranExecuteNonQuery(xufeisql, tran);
                            //财务子表处理
                            findetailsql = finDetailAdd((JObject)detailArr[i], fmainInsertedId, edNumber, mainOrderModeltemp, financemainmodeltemp);//财务明细表增加
                            DbUtils.tranExecuteNonQuery(findetailsql, tran);
                            break;
                        case "新增":
                            ccc = ccc + 1;
                            string addsql = orderDetailAdd((JObject)detailArr[i], mainOrderModeltemp, edNumber);//把模型参数带进去作为变量使用
                            //DbUtils.tranExecuteNonQuery(addsql, tran);
                            int orderDetailInsertId = 0;
                            orderDetailInsertId = DbUtils.tranInsert(addsql, tran);
                            //财务子表处理
                            findetailsql = finDetailAdd((JObject)detailArr[i], fmainInsertedId, edNumber, mainOrderModeltemp, financemainmodeltemp, orderDetailInsertId);//财务明细表增加
                            DbUtils.tranExecuteNonQuery(findetailsql, tran);
                            break;

                        default:
                            break;
                    }

                    //更新房间到期时间  用于房间显示状态
                    if (detailArr[i]["serviceId"].ToString() == "3")
                    {
                        //更新房间表  只执行一次
                        MJRoomsModel roomModel = new MJRoomsModel();
                        DateTime edt = DateTime.Parse(detailArr[i]["exp_time"].ToString());
                        DateTime nextpaydate=edt.AddDays(-5);//下次付款时间比原来少5天
                        string roomsql = "update MJRooms set add_time='"+ detailArr[i]["add_time"].ToString() + "',exp_time='"+ detailArr[i]["exp_time"].ToString() + "',nextpaydate='"+nextpaydate.ToString()+"' where keyid=" + detailArr[i]["roomid"].ToString() + " ";
                        DbUtils.tranUpdate(roomsql,tran);//
                        //更新房间表 只执行一次

                        //如果包含房租 更新订单主表
                        MJOrderModel fo = new MJOrderModel();
                        fo.KeyId = int.Parse(orderid);
                        fo.nextpaydate = nextpaydate;
                        string[] upfiles = { "nextpaydate" };//只更新nextpaydate这个字段
                        DbUtils.tranUpdateOnlyUpdateFields(fo, tran, upfiles);


                    }



                }



                switch (c)
                {
                    case 2://有两个收款账户的情况
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifub + " where KeyId=" + accountidb + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifuc + " where KeyId=" + accountidc + "", tran);
                        break;
                    case 3:
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifub + " where KeyId=" + accountidb + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifuc + " where KeyId=" + accountidc + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifud + " where KeyId=" + accountidd + "", tran);
                        break;

                    default://有一个收款账户的情况
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + payment + " where KeyId=" + accountid + "", tran);
                        break;
                }



                if (ccc == 0)
                {
                    context.Response.Write("{\"status\":0,\"msg\":\"失败！没有更新任何数据！\"}");
                    tran.Rollback();//事务回滚
                    //context.Response.End();
                }
                else
                {
                    tran.Commit();//提交执行事务
                    LogModel log = new LogModel();
                    log.BusinessName = "续费办理成功";
                    log.OperationIp = PublicMethod.GetClientIP();
                    log.OperationTime = DateTime.Now;
                    log.PrimaryKey = "";
                    log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                    log.TableName = "";
                    log.note = "财务主表id:"+fmainInsertedId+";订单id:"+edNumber+"";
                    log.OperationType = (int)OperationType.Other;
                    LogDal.Instance.Insert(log);

                    context.Response.Write("{\"status\":1,\"msg\":\"提交成功！\",\"edNumber\":\"" + edNumber + "\"}");
                }



                #endregion


                #region 新增部分处理

                #endregion
            }
            catch (Exception e)
            {
                LogModel log = new LogModel();
                log.BusinessName = "续费办理失败";
                log.OperationIp = PublicMethod.GetClientIP();
                log.OperationTime = DateTime.Now;
                log.PrimaryKey = "";
                log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                log.TableName = "";
                log.note = e.ToString();
                log.OperationType = (int)OperationType.Other;
                LogDal.Instance.Insert(log);
                tran.Rollback();//错误！事务回滚！
                context.Response.Write("{\"status\":0,\"msg\":\"" + e.Message + "\"}");
            }






        }

        /// <summary>
        /// 财务字表明细增加处理
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string finDetailAdd(JObject o, int fmainInsertedId, string edNumber, MJOrderModel ordermainmodel, MJFinanceMainModel financemainmodel, int orderDetailInsertId = 0)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append("insert into MJFinanceDetail ");
            sb.Append("(");//字段开始
            //sb.Append("KeyId,");//编号
            sb.Append("financeId,");//主表ID
            //sb.Append("ftype,");//收支类型
            sb.Append("edNumber,");//编号
            sb.Append("subject,");//科目
            sb.Append("subjectid,");//科目ID
            sb.Append("sumMoney,");//金额
            //sb.Append("dep,");//部门
            sb.Append("depid,");//部门ID
            sb.Append("note,");//备注
            sb.Append("add_time,");//添加时间
            sb.Append("up_time,");//更新时间
            //sb.Append("ownner,");//数据所有者ID
            sb.Append("paytype,");//
            sb.Append("nextpaydate,");//
            //--新增的--
            sb.Append("userid,");//客户ID
            sb.Append("username,");//客户姓名
            sb.Append("contact,");//联系人姓名
            sb.Append("contactid,");//联系人ID
            sb.Append("stime,");//开始时间
            sb.Append("etime,");//结束时间
            sb.Append("num,");//服务数量
            sb.Append("sprice,");//服务单价
            sb.Append("mobile,");//手机号
            sb.Append("orderdetailid,");//财务关联服务的ID
            //--新增的--

            sb.Append("roomid,");//
            sb.Append("roomno");//
            sb.Append(")");//字段结束
            sb.Append(" values ");
            sb.Append("(");//值开始
            //sb.Append("'" + o["KeyId"].ToString() + "',");//编号 int
            sb.Append("'" + fmainInsertedId + "',");//主表ID int
            //sb.Append("'" + o["ftype"].ToString() + "',");//收支类型 varchar
            sb.Append("'" + edNumber + "',");//编号 varchar
            sb.Append("'" + o["serviceName"].ToString() + "',");//科目 varchar
            sb.Append("" + o["serviceId"].ToString() + ",");//科目ID int
            sb.Append("" + o["newallprice"].ToString() + ",");//金额 money
            //sb.Append("'" + o["dep"].ToString() + "',");//部门 varchar
            sb.Append("'" + financemainmodel.depid + "',");//部门ID int
            sb.Append("'" + o["note"].ToString() + "',");//备注 varchar
            sb.Append("'" + o["add_time"].ToString() + "',");//添加时间 datetime
            sb.Append("'" + o["exp_time"].ToString() + "',");//更新时间 datetime
            //sb.Append("'" + o["ownner"].ToString() + "',");//数据所有者ID int
            sb.Append("'" + ordermainmodel.paytype + "',");// 支付方式
            sb.Append("'" + ordermainmodel.nextpaydate + "',");// datetime
                                                               //--新增的--
            sb.Append("" + ordermainmodel.usersid + ",");//客户ID
            sb.Append("'" + ordermainmodel.users + "',");//客户姓名
            sb.Append("'" + financemainmodel.contact + "',");//联系人姓名
            sb.Append("" + financemainmodel.contactid + ",");//联系人ID
            sb.Append("'" + o["add_time"].ToString() + "',");//开始时间
            sb.Append("'" + o["exp_time"] + "',");//结束时间
            sb.Append("'" + o["num"].ToString() + "',");//服务数量
            sb.Append("'" + o["sprice"].ToString() + "',");//服务单价
            sb.Append("'" + ordermainmodel.mobile + "',");//手机号
            if (orderDetailInsertId == 0)
            {
                sb.Append("" + o["KeyId"].ToString() + ",");//刚刚插入的服务明细ID
            }
            else
            {
                sb.Append("" + orderDetailInsertId + ",");//刚刚插入的服务明细ID
            }

            //--新增的--

            sb.Append("" + ordermainmodel.roomid + ",");// int
            sb.Append("'" + ordermainmodel.roomno + "'");// 房间号
            sb.Append(")");//值结束

            return sb.ToString();
        }





        /// <summary>
        /// 新增订单明细处理
        /// </summary>
        /// <param name="o"></param>
        /// <param name="ordermainmodel"></param>
        /// <param name="edNumber"></param>
        /// <returns></returns>

        public static string orderDetailAdd(JObject o, MJOrderModel ordermainmodel, string edNumber)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("insert into MJOrderDetail ");
            sb.Append("(");//字段开始
            //sb.Append("KeyId,");//系统编号
            sb.Append("MJOrderid,");//订单ID
            sb.Append("serviceName,");//服务名称
            sb.Append("serviceId,");//银行科目ID
            sb.Append("sprice,");//单价
            sb.Append("num,");//数量
            sb.Append("allprice,");//总价
            //sb.Append("dep,");//部门名称
            sb.Append("depid,");//部门id
            sb.Append("add_time,");//服务开始时间
            sb.Append("exp_time,");//到期时间
            sb.Append("note,");//备注
            //sb.Append("ownner,");//数据所有者ID
            //sb.Append("contact,");//经手人
            //sb.Append("contactid,");//经手人ID
            sb.Append("users,");//客户
            sb.Append("usersid,");//用户ID
            sb.Append("roomno,");//房间号
            sb.Append("roomid,");//房间ID
            sb.Append("edNumber,");//系统生成的订单ID
            sb.Append("orderstatus,");//0正常-1结单
            sb.Append("htstate");//是否已确定合同标识0没打1已经打了
            //sb.Append("paytype,");//
            //sb.Append("nextpaydate");//
            sb.Append(")");//字段结束
            sb.Append(" values ");
            sb.Append("(");//值开始
            //sb.Append("'" + o["KeyId"].ToString() + "',");//系统编号 int
            sb.Append("" + ordermainmodel.KeyId + ",");//订单ID int
            sb.Append("'" + o["serviceName"].ToString() + "',");//服务名称 varchar
            sb.Append("" + o["serviceId"].ToString() + ",");//银行科目ID int
            sb.Append("" + o["newsprice"].ToString() + ",");//单价 money
            sb.Append("" + o["newnum"].ToString() + ",");//数量 int
            sb.Append("" + o["newallprice"].ToString() + ",");//总价 money
            //sb.Append("'" + o["dep"].ToString() + "',");//部门名称 varchar
            sb.Append("'" + SysVisitor.Instance.cookiesUserDepId + "',");//部门id int
            sb.Append("'" + o["add_time"].ToString() + "',");//服务开始时间 datetime
            sb.Append("'" + o["exp_time"].ToString() + "',");//到期时间 datetime
            sb.Append("'" + o["note"].ToString() + "',");//备注 varchar
            //sb.Append("'" + o["ownner"].ToString() + "',");//数据所有者ID int
            //sb.Append("'" + o["contact"].ToString() + "',");//经手人 varchar
            //sb.Append("'" + o["contactid"].ToString() + "',");//经手人ID int
            sb.Append("'" + ordermainmodel.users + "',");//客户 varchar
            sb.Append("" + ordermainmodel.usersid + ",");//用户ID int
            sb.Append("'" + ordermainmodel.roomno + "',");//房间号 varchar
            sb.Append("" + ordermainmodel.roomid + ",");//房间ID int
            sb.Append("'" + edNumber + "',");//系统生成的订单ID varchar
            sb.Append("0,");//0正常-1结单 int
            sb.Append("0");//是否已确定合同标识0没打1已经打了 int
            //sb.Append("'" + o["paytype"].ToString() + "',");// varchar
            //sb.Append("'" + o["nextpaydate"].ToString() + "',");// datetime
            sb.Append(") select @@identity");//值结束
            return sb.ToString();
        }



        /// <summary>
        /// 续费处理
        /// </summary>
        /// <returns></returns>
        public static string orderDetailxf(JObject o)
        {
            //更新语句
            StringBuilder sb = new StringBuilder();
            sb.Append("update MJOrderDetail");
            sb.Append(" set ");
            //sb.Append("KeyId='" + o["KeyId"].ToString() + "'");//系统编号 int
            //sb.Append(",MJOrderid='" + o["MJOrderid"].ToString() + "'");//订单ID int
            //sb.Append(",serviceName='" + o["serviceName"].ToString() + "'");//服务名称 varchar
            //sb.Append(",serviceId='" + o["serviceId"].ToString() + "'");//银行科目ID int
            sb.Append("sprice=" + o["newsprice"].ToString() + "");//单价 money
            sb.Append(",num=" + o["newnum"].ToString() + "");//数量 int
            sb.Append(",allprice=" + o["newallprice"].ToString() + "");//总价 money
            //sb.Append(",dep='" + o["dep"].ToString() + "'");//部门名称 varchar
            //sb.Append(",depid='" + o["depid"].ToString() + "'");//部门id int
            sb.Append(",add_time='" + o["add_time"].ToString() + "'");//服务开始时间 datetime
            sb.Append(",exp_time='" + o["exp_time"].ToString() + "'");//到期时间 datetime
            sb.Append(",note='" + o["note"].ToString() + "'");//备注 varchar
                                                              //sb.Append(",ownner='" + o["ownner"].ToString() + "'");//数据所有者ID int
                                                              //sb.Append(",contact='" + o["contact"].ToString() + "'");//经手人 varchar
                                                              //sb.Append(",contactid='" + o["contactid"].ToString() + "'");//经手人ID int
                                                              //sb.Append(",users='" + o["users"].ToString() + "'");//客户 varchar
                                                              //sb.Append(",usersid='" + o["usersid"].ToString() + "'");//用户ID int
                                                              //sb.Append(",roomno='" + o["roomno"].ToString() + "'");//房间号 varchar
                                                              //sb.Append(",roomid='" + o["roomid"].ToString() + "'");//房间ID int
                                                              //sb.Append(",edNumber='" + o["edNumber"].ToString() + "'");//系统生成的订单ID varchar
                                                              //sb.Append(",orderstatus='" + o["orderstatus"].ToString() + "'");//0正常-1结单 int
                                                              //sb.Append(",htstate='" + o["htstate"].ToString() + "'");//是否已确定合同标识0没打1已经打了 int
                                                              //sb.Append(",paytype='" + o["paytype"].ToString() + "'");// varchar
                                                              //sb.Append(",nextpaydate='" + o["nextpaydate"].ToString() + "'");// datetime
            sb.Append(" where KeyId=" + o["KeyId"].ToString() + "");
            return sb.ToString();
        }



        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}